﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LoginControl = System.Web.UI.WebControls.Login;
using System.Security;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.IdentityModel;
using System.IdentityModel.Tokens;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.IdentityModel.Pages;


namespace JM.JCY.MasterPage.Login
{
    public partial class SPLogin : IdentityModelSignInPageBase
    {
        protected LoginControl loginControl;
        protected EncodedLiteral ClaimsFormsPageMessage;
      
    

        protected void Page_Load(object sender, EventArgs e)
        {
            GetIE();
            if (GetIE())
            {
                lblIEFix.Visible = false;
            }
        

             try
            {
                ClaimsFormsPageMessage.Text = "";
                loginControl.Focus();
         
                           }
            catch (Exception ex)
            {

                Response.Write(ex.Message);
            }  
        }

        private bool GetIE()
        {
            string browser = Request.Browser.Browser;
            string browserVersion = Request.Browser.Version;
            string userAgent = Request.UserAgent;

            try
            {
                string version = browserVersion.Substring(0, 1);
                if (browser != "IE" || Int32.Parse(version) < 7)
                {
                    this.lblBrowser.Visible = true;

                    this.lblBrowser.Text = "您当前的浏览器版本为 " + browser + " " + browserVersion + ",请先安装 IE 8.0 版本的浏览器，然后使用 IE 8.0 浏览器登陆系统。";
                    
                    if (userAgent.Contains("NT 5.1") || userAgent.Contains("NT 5"))
                    {
                        xp.HRef = @"http://10.135.116.167:88/iedownload/IE8安装程序xp.exe";
                      
                        this.xp.Visible = true;
                      
                    }

                    if (userAgent.Contains("NT 5.2"))
                    {
                        xp.HRef = @"http://10.135.116.167:88/iedownload/IE8安装程序win2003.exe";
                        this.xp.Visible = true;
                    }
                    
                    if (userAgent.Contains("NT 6.0"))
                    {
                        xp.HRef = @"http://10.135.116.167:88/iedownload/IE8安装程序vista.exe";
                        this.xp.Visible = true;
                    }

                    return false;
                    
                }
            }

            catch (Exception)
            {

                this.lblBrowser.Visible = true;
                this.lblBrowser.Text = "您当前的浏览器版本为 " + browser + " " + browserVersion + ",请先安装 IE 8.0 版本的浏览器，然后使用 IE 8.0 浏览器登陆系统。";

                if (userAgent.Contains("NT 5.1") || userAgent.Contains("NT 5"))
                {
                    xp.HRef = @"http://10.135.116.167:88/iedownload/IE8安装程序xp.exe";

                    this.xp.Visible = true;

                }

                if (userAgent.Contains("NT 5.2"))
                {
                    xp.HRef = @"http://10.135.116.167:88/iedownload/IE8安装程序win2003.exe";
                    this.xp.Visible = true;
                }

                if (userAgent.Contains("NT 6.0"))
                {
                    xp.HRef = @"http://10.135.116.167:88/iedownload/IE8安装程序vista.exe";
                    this.xp.Visible = true;
                }

                return false;
            }
          
            return true;
        }

        /// <summary>
        /// 验证登录信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void signInControl_LoggingIn(object sender, LoginCancelEventArgs e)
        {
            LoginControl login = sender as LoginControl;
            login.UserName = login.UserName.Trim();
            if (string.IsNullOrEmpty(login.UserName) || !GetIE())
            {
                ClaimsFormsPageMessage.Text = "The server could not sign you in. The user name cannot be empty.";
                e.Cancel = true;
            }
          
        }

        /// <summary>
        /// 根据安全令牌执行登录
        /// </summary>
        /// <param name="securityToken">安全令牌</param>
        private void EstablishSessionWithToken(SecurityToken securityToken)
        {
            if (null == securityToken)
            {
                throw new ArgumentNullException("securityToken");
            }
            SPFederationAuthenticationModule fam = SPFederationAuthenticationModule.Current;
            if (null == fam)
            {
                throw new ArgumentException(null, "FederationAuthenticationModule");
            }

            fam.SetPrincipalAndWriteSessionToken(securityToken);
        }

        /// <summary>
        /// 登录事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void signInControl_Authenticate(object sender, AuthenticateEventArgs e)
        {
            SecurityToken token = null;
            LoginControl formsLoginControl = sender as LoginControl;

            if (null != (token = GetSecurityToken(formsLoginControl)))
            {
                EstablishSessionWithToken(token);
                e.Authenticated = true;
                base.RedirectToSuccessUrl();
            }
        }

        /// <summary>
        /// 获取当前web.congif
        /// </summary>
        private SPIisSettings IisSettings
        {
            get
            {

                SPWebApplication webApp = SPWebApplication.Lookup(new Uri(SPContext.Current.Web.Url));
                SPIisSettings settings = webApp.IisSettings[SPUrlZone.Default];
                return settings;
            }
        }
        /// <summary>
        /// 设置安全令牌
        /// </summary>
        /// <param name="formsLoginControl">登陆控件</param>
        /// <returns> 安全令牌</returns>
        private SecurityToken GetSecurityToken(LoginControl formsLoginControl)
        {
            SecurityToken token = null;
            SPIisSettings iisSettings = IisSettings;
            Uri appliesTo = base.AppliesTo;

            if (string.IsNullOrEmpty(formsLoginControl.UserName) ||
                string.IsNullOrEmpty(formsLoginControl.Password))
                return null;

            SPFormsAuthenticationProvider authProvider = iisSettings.FormsClaimsAuthenticationProvider;
            token = SPSecurityContext.SecurityTokenForFormsAuthentication(
                appliesTo,
                authProvider.MembershipProvider,
                authProvider.RoleProvider,
                formsLoginControl.UserName,
                formsLoginControl.Password);

            return token;
        }

        private string GetOSNameByUserAgent(string userAgent)
        {
            string osVersion = "未知";
            if (userAgent.Contains("NT 6.0"))
            {
                osVersion = "Windows Vista/Server 2008";
            }
            else if (userAgent.Contains("NT 5.2"))
            {
                osVersion = "Windows Server 2003";
            }
            else if (userAgent.Contains("NT 5.1"))
            {
                osVersion = "Windows XP";
            }
            else if (userAgent.Contains("NT 5"))
            {
                osVersion = "Windows 2000";
            }
            else if (userAgent.Contains("NT 4"))
            {
                osVersion = "Windows NT4";
            }
            else if (userAgent.Contains("Me"))
            {
                osVersion = "Windows Me";
            }
            else if (userAgent.Contains("98"))
            {
                osVersion = "Windows 98";
            }
            else if (userAgent.Contains("95"))
            {
                osVersion = "Windows 95";
            }
            else if (userAgent.Contains("Mac"))
            {
                osVersion = "Mac";
            }
            else if (userAgent.Contains("Unix"))
            {
                osVersion = "UNIX";
            }
            else if (userAgent.Contains("Linux"))
            {
                osVersion = "Linux";
            }
            else if (userAgent.Contains("SunOS"))
            {
                osVersion = "SunOS";
            }
            return osVersion;
        }


       }
}